<template>
  <div class="app-container">
     <!-- 数据看板 -->
           

    <el-form :inline="true" :model="queryParams" style="margin-bottom: 16px;">
      <el-form-item label="载体">
        <el-select
          v-model="queryParams.zt"
          placeholder="请选择载体"
          style="width: 200px"
          @change="handleQuery"
        >
          <el-option
            v-for="item in carrierList"
            :key="item.nr"
            :label="item.nr"
            :value="item.nr"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="月份">
        <el-date-picker
          v-model="queryParams.month"
          type="month"
          value-format="YYYY-MM"
          placeholder="请选择月份"
          style="width: 140px"
          @change="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
        <el-button type="primary" @click="triggerImport">Excel导入</el-button>
      </el-form-item>
    </el-form>
   <div class="dashboard">
                <!-- <div class="dashboard-row">
                 
                </div> -->
                 <div class="dashboard-item board-blue">
                    <span class="label">整体客户数</span>
                    <span class="value">{{ dashboard.saa }}</span>
                  </div>
                  <div class="dashboard-item board-blue">
                    <span class="label">已匹配数</span>
                    <span class="value">{{ dashboard.sab }}</span>
                  </div>
                <!-- <div class="dashboard-row">
                  
                  
                </div> -->
                <div class="dashboard-item board-green">
                    <span class="label">未匹配数</span>
                    <span class="value highlight">{{ dashboard.sac }}</span>
                  </div>
                  <div class="dashboard-item board-green">
                    <span class="label">空调应收</span>
                    <span class="value">{{ dashboard.ktf }}</span>
                  </div>
              </div>
    <!-- 列表 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="margin-top: 20px"
    >
      <el-table-column prop="zt" label="项目" align="center" />
      <!-- <el-table-column prop="fjh" label="房间号" align="center" /> -->
      <el-table-column prop="qymc" label="企业名称" align="center" width="320" />
      <el-table-column prop="nf" label="计费归属年" align="center" />
      <el-table-column prop="yf" label="计费归属月" align="center" />
      <el-table-column prop="dbs" label="用电量" align="center" />
      <el-table-column prop="ktfje" label="空调费" align="center" />
      <el-table-column prop="khbh" label="匹配标识" align="center" />
    </el-table>
   
 <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- Excel导入弹窗 -->
    <el-dialog
      title="Excel数据预览"
      v-model="importDialogVisible"
      width="60%"
      :close-on-click-modal="false"
      @close="clearImportData"
    >
      <el-table
        :data="importPreviewData"
        height="400"
        border
        style="margin-bottom: 16px"
      >
        <el-table-column
          v-for="col in importPreviewColumns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          align="center"
        />
      </el-table>
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmImport">确定</el-button>
      </template>
    </el-dialog>

    <input
      ref="fileInput"
      type="file"
      accept=".xlsx,.xls"
      style="display: none"
      @change="handleFileChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import * as XLSX from "xlsx";
import { insertKtfy, airConditioningMatch, airConditioningList } from '@/api/bill/index';
import { selectzt } from "@/api/carrier/ammeter";
import { parseTime } from "@/utils/ruoyi";

const { proxy } = getCurrentInstance();

const fileInput = ref(null);
const tableData = ref([]);
const total = ref(0);
const dashboard = ref({});
const loading = ref(false);

const queryParams = reactive({
  zt: undefined,
  month: getLastMonthStr(),
  pageNum: 1,
  pageSize: 10,
});

const carrierList = ref([]);

// 数字看板
function getBoardData() {
  airConditioningMatch({
    zt: queryParams.zt,
    month: queryParams.month,
  }).then(res => {
    dashboard.value = res.data || {};
  });
}

// 列表
function getList() {
  loading.value = true;
  airConditioningList({
    zt: queryParams.zt,
    month: queryParams.month,
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
  }).then(res => {
    tableData.value = res.data?.list || [];
    total.value = res.data?.total || 0;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
  });
}

function handleQuery() {
  queryParams.pageNum = 1;
  getBoardData();
  getList();
}
function resetQuery() {
  queryParams.month = getLastMonthStr();
  if (carrierList.value.length > 0) {
    queryParams.zt = carrierList.value[0].nr;
  }
  queryParams.pageNum = 1;
  getBoardData();
  getList();
} 

// 获取载体下拉
function getCarrierList() {
  selectzt({
    pageNum: 1,
    pageSize: 20,
    lxbh: 1,
  }).then(res => {
    carrierList.value = res.data?.list || [];
    if (carrierList.value.length > 0) {
      queryParams.zt = carrierList.value[0].nr;
      handleQuery();
    }
  });
}

function getLastMonthStr() {
  const d = new Date();
  d.setDate(1);
  d.setMonth(d.getMonth() - 1);
  return parseTime(d, "{y}-{m}");
}

// Excel导入弹窗相关
const importDialogVisible = ref(false);
const importPreviewData = ref([]);
const importPreviewColumns = ref([
  { prop: "date", label: "时间" },
  { prop: "room", label: "房间号" },
  { prop: "username", label: "用户名" },
  { prop: "building", label: "楼栋" },
  { prop: "floor", label: "楼层" },
  { prop: "totalPower", label: "总电量(kWh)" },
  { prop: "totalCost", label: "总费用(元)" },
]);
const importResult = ref({});

function triggerImport() {
  fileInput.value && fileInput.value.click();
}
function handleFileChange(e) {
  const files = e.target.files;
  if (!files.length) return;
  const file = files[0];
  const reader = new FileReader();
  reader.onload = (evt) => {
    const data = evt.target.result;
    const workbook = XLSX.read(data, { type: "binary" });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { defval: "" });
    const dataRows = jsonData.slice(2);
    importPreviewData.value = processData(dataRows);
    importDialogVisible.value = true;
    importResult.value = {
      dataRows: JSON.stringify(importPreviewData.value),
      date: queryParams.month || "",
      zt: queryParams.zt || "",
    };
  };
  reader.readAsBinaryString(file);
}
function clearImportData() {
  importPreviewData.value = [];
  importDialogVisible.value = false;
}
function confirmImport() {
  insertKtfy(importResult.value).then(res => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess("数据导入成功");
      clearImportData();
      getList();
    } else {
      proxy.$modal.msgError("数据导入失败: " + res.msg);
    }
  }).catch(err => {
    proxy.$modal.msgError("数据导入异常: " + err.message);
  });
}

// 处理Excel数据
function processData(data) {
  let currentDate = null;
  const groupedData = {};
  data.forEach(row => {
    if (!row.__EMPTY_2 || !row.__EMPTY_5) return;
    const date = row.__EMPTY_1 || currentDate;
    if (date) currentDate = date;
    let room = row.__EMPTY_5;
    if (typeof room === 'string' && room.length > 5) {
      const mid = Math.floor(room.length / 2);
      const part1 = parseInt(room.slice(0, mid), 10);
      const part2 = parseInt(room.slice(mid), 10);
      if (!isNaN(part1) && !isNaN(part2)) {
        room = part1 < part2 ? part1 : part2;
      }
    }
    const key = `${date}|${room}`;
    if (!groupedData[key]) {
      groupedData[key] = {
        date: date,
        room: room,
        username: row.__EMPTY_2,
        building: row.__EMPTY_3,
        floor: row.__EMPTY_4,
        totalPower: 0,
        totalCost: 0
      };
    }
    const power = parseFloat(row.__EMPTY_7) || 0;
    const cost = parseFloat(row.__EMPTY_8) || 0;
    groupedData[key].totalPower += power;
    groupedData[key].totalCost += cost;
  });
  return Object.values(groupedData).map(item => ({
    ...item,
    totalPower: item.totalPower.toFixed(2),
    totalCost: item.totalCost.toFixed(2)
  }));
}

onMounted(() => {
  getCarrierList();
});
</script>
<style scoped>

.dashboard {
  background: #fafdff;
  border-radius: 18px;
  box-shadow: 0 4px 18px rgba(32, 159, 240, 0.1);
  padding: 28px 18px 18px 18px;
  margin-bottom: 36px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.dashboard-row {
  /* display: flex;
  justify-content: space-between;
  gap: 18px;
  margin-bottom: 0; */
}
.dashboard-item {
  flex: 1;
  margin-right: 0;
  background: linear-gradient(135deg, #eaf6ff 0%, #fafdff 100%);
  border-radius: 14px;
  padding: 22px 0 16px 0;
  text-align: center;
  box-shadow: 0 2px 8px rgba(32, 159, 240, 0.06);
  border: 1.5px solid #e6f3fc;
  transition: box-shadow 0.2s;
  position: relative;
  overflow: hidden;
}
.dashboard-item:not(:last-child) {
  margin-right: 18px;
}
.label {
  font-size: 16px;
  color: #7a8fa7;
  display: block;
  margin-bottom: 10px;
  letter-spacing: 1px;
  font-weight: 500;
}
.value {
  font-size: 30px;
  font-weight: bold;
  color: #222;
  display: block;
  letter-spacing: 1px;
  line-height: 1.2;
}
.value.highlight {
  color: #209ff0;
}
.board-blue {
  border-left: 5px solid #209ff0;
  background: linear-gradient(90deg, #eaf6ff 0%, #fafdff 100%);
}
.board-green {
  border-left: 5px solid #67c23a;
  background: linear-gradient(90deg, #eafff3 0%, #fafdff 100%);
}
.board-orange {
  border-left: 5px solid #faad14;
  background: linear-gradient(90deg, #fff7e6 0%, #fafdff 100%);
}
</style>